﻿using ChiDao.Business.Data.Initialize;
using ChiDao.Business.Data.Repositories.Account;
using ChiDao.Business.Models.Account;
using ChiDao.Business.Models.Security;
using ChiDao.Business.Service;
using ChiDao.Business.Service.Impl;
using ChiDao.Component.Utils;
using ChiDao.Site.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ChiDao.Consoles
{
    [Export]
    internal class Program
    {
        private static CompositionContainer _container;

        [Import]
        public IOrgService OrgContract { get; set; }

        [Import]
        public IActionInfoService ActionInfoContract { get; set; }

        #region 主程序

        private static void Main(string[] args)
        {
            //初始化MEF组合容器
            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(Directory.GetCurrentDirectory()));
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new CompositionContainer(catalog);
            DatabaseInitializer.Initialize();

            bool exit = false;
            while (true)
            {
                try
                {
                    Console.Write("=========================================================");
                    Console.WriteLine(@"
1.ViewModel To Model
2.MD5盐值加密
3.String转Guid
4.获取所有ActionInfo
5.获取Northow的菜单
6.获取所有MenuInfo
请输入命令：0; 退出程序，功能命令：1 - n");
                    string input = Console.ReadLine();
                    if (input == null)
                    {
                        continue;
                    }
                    switch (input.ToLower())
                    {
                        case "0":
                            exit = true;
                            break;
                        case "1":
                            ViewModelToModel();
                            break;
                        case "2":
                            MD5Encrypt();
                            break;
                        case "3":
                            StringToGuid();
                            break;
                        case "4":
                            GetAllActionByAssembly();
                            break;
                        case "5":
                            GetMenusByUserID();
                            break;
                        case "6":
                            GetAllMenuInfoByAssembly();
                            break;
                        case "7":
                            Method07();
                            break;
                        case "8":
                            Method08();
                            break;
                        case "9":
                            Method09();
                            break;
                        case "10":
                            Method10();
                            break;
                        case "11":
                            Method11();
                            break;
                        case "12":
                            Method12();
                            break;
                        case "13":
                            Method13();
                            break;
                        case "14":
                            Method14();
                            break;
                    }
                    if (exit)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    ExceptionHandler(e);
                }
            }
        }

        private static void ExceptionHandler(Exception e)
        {
            ExceptionMessage emsg = new ExceptionMessage(e);
            Console.WriteLine(emsg.ErrorDetails);
        }

        #endregion

        #region 功能方法

        /// <summary>
        /// ViewModel转为Model
        /// </summary>
        private static void ViewModelToModel()
        {
            OrgView viewModel = new OrgView();  //初始化ViewModel对象

            //给ViewModel对象赋值
            viewModel.ID = GuidHelper.NewGuid();
            viewModel.OrgNo = "1000";
            viewModel.OrgName = "部门名称";

            Org model = viewModel.CopyTo<Org>();  //ViewModel对象的属性值赋值给Model对象对应的属性（扩展方法形式）

            Console.WriteLine(string.Format("ID：{0}，OrgNo：{1}，OrgName：{2}", model.ID, model.OrgNo, model.OrgName));
        }

        /// <summary>
        /// MD5盐值加密
        /// </summary>
        private static void MD5Encrypt()
        {
            //IMemberRepository memberRepository = _container.GetExportedValue<IMemberRepository>();
            //List<Member> members = memberRepository.Entities.Include(m => m.Roles).ToList();
            //foreach (var member in members)
            //{
            //    Console.WriteLine(member.Roles.Count);
            //}

            string inputPassword = "123456";
            //string md5Password = EncryptHelper.MD5Encoding(inputPassword);  //MD5加密
            string md5SaltPassword = EncryptHelper.ToMD5Salt(inputPassword);  //MD5盐值加密
            //Console.WriteLine(string.Format("原始密码：{0}\nMD5密码：{1}\nMD5盐值密码：{2}", inputPassword, md5Password, md5SaltPassword));
            Console.WriteLine(string.Format("原始密码：{0}\nD5盐值密码：{1}", inputPassword, md5SaltPassword));
        }

        /// <summary>
        /// String转为Guid
        /// </summary>
        private static void StringToGuid()
        {
            //IMemberRepository memberRepository = _container.GetExportedValue<IMemberRepository>();
            //var members = memberRepository.Entities.Select(m => new
            //{
            //    Roles = new { Count = m.Roles.Count }
            //}).ToList();
            //foreach (var member in members)
            //{
            //    Console.WriteLine(member.Roles.Count);
            //}
            string strGuid = GuidHelper.NewGuid().ToString();
            Guid result = strGuid.ToGuid();
            Console.WriteLine("String转Guid：" + result.ToString());
        }

        /// <summary>
        /// 反射获取所有Controller的Action列表
        /// </summary>
        private static void GetAllActionByAssembly()
        {
            List<ActionInfo> result = new List<ActionInfo>();

            //IActionInfoService ActionInfoContract = new ActionInfoService();  //暂时通过实例化方式实现（测试时需要把internal修改为public）
            IActionInfoService ActionInfoContract = _container.GetExportedValue<IActionInfoService>();
            result = ActionInfoContract.GetAllActionInfoByAssembly().ToList();
            foreach (ActionInfo item in result)
            {
                Console.WriteLine("Action名称：" + item.ActionName + "，Controller名称：" + item.ControllerName + "，描述：" + item.Description);
            }
        }

        /// <summary>
        /// 根据UserID获取菜单
        /// </summary>
        private static void GetMenusByUserID()
        {
            //IMemberRepository memberRepository = _container.GetExportedValue<IMemberRepository>();
            //Member member = memberRepository.Entities.First();
            //member.AddDate = DateTime.Now;
            //memberRepository.Update(member);
            //Console.WriteLine(memberRepository.Entities.First().AddDate);

            /*
             var result = new List<Menu>();
            var user = Members.FirstOrDefault(m => m.ID == userID);
            if (user != null)
            {
                result = user.Menus.ToList();
            }
            return result;
             */

            string userID = "7FC7BB5C-DD2F-447E-AC36-A254009D6F3C";  //northow对应的ID
            //string userID = "E8A2FE06-97AA-48CC-BE9E-A254009D6F3C";  //admin对应的ID
            Guid userGuid = userID.ToGuid();

            IPersonRepository personRepository = _container.GetExportedValue<IPersonRepository>();
            Person person = personRepository.Entities.FirstOrDefault(m => m.ID == userGuid);

            List<MenuInfo> menus = new List<MenuInfo>();
            menus = person.MenuInfoes.OrderBy(m => m.MenuCode).ThenBy(m => m.MenuName).ToList();

            Console.WriteLine("Northow所拥有的菜单：");
            foreach (MenuInfo item in menus)
            {
                Console.WriteLine("MenuCode：" + item.MenuCode + "，MenuName：" + item.MenuName + "，描述：" + item.Description);
            }
        }

        private static void GetAllMenuInfoByAssembly()
        {
            //IMemberRepository memberRepository = _container.GetExportedValue<IMemberRepository>();
            //Member member = new Member {ID = 1, AddDate = DateTime.Now};
            //memberRepository.Update(m => new {m.AddDate}, member);
            //Console.WriteLine(memberRepository.Entities.First().AddDate);

            List<MenuInfo> result = new List<MenuInfo>();

            //IActionInfoService ActionInfoContract = new ActionInfoService();  //暂时通过实例化方式实现（测试时需要把internal修改为public）
            IMenuInfoService menuInfoContract = _container.GetExportedValue<IMenuInfoService>();
            result = menuInfoContract.GetAllMenuInfoByAssembly().ToList();
            foreach (MenuInfo item in result)
            {
                Console.WriteLine("Action名称：" + item.ActionName + "，Controller名称：" + item.ControllerName + "，描述：" + item.Description);
            }
        }

        private static void Method07()
        {
            throw new NotImplementedException();
        }

        private static void Method08()
        {
            throw new NotImplementedException();
        }

        private static void Method09()
        {
            throw new NotImplementedException();
        }

        private static void Method10()
        {
            throw new NotImplementedException();
        }

        private static void Method11()
        {
            throw new NotImplementedException();
        }

        private static void Method12()
        {
            throw new NotImplementedException();
        }

        private static void Method13()
        {
            throw new NotImplementedException();
        }

        private static void Method14()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}